import emitter from '@/utils/emitter';
import Events from '@/utils/event';
import { noop } from 'lodash-es';

const CgTable = {
  data () {
    return {
      // defaultExpandAllRows 这个属性，需要先获取数据
      // 为了解决这个问题，给 table 设置一个key，获取数据之后改变这个key值，借助了key改变自动变成新的 component 来解决这个问题
      tableKey: 1,
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 1,
        showSizeChanger: false,
        showQuickJumper: true,
        size: 'middle'
      },
      selectedRowKeys: [],
      tableData: []
    };
  },
  props: {
    showRowSelection: {
      type: Boolean,
      default: true
    },
    showAllList: {
      type: Boolean,
      default: false
    },
    showButton: {
      type: Boolean,
      default: true
    },
    tableHeader: {
      type: Array,
      default: () => ([])
    },
    getList: {
      type: Function
    },
    deleteData: {
      type: Function
    }
  },
  methods: {
    refreshTable (isFirstPage) {
      isFirstPage && (this.pagination.current = 1);
      this.loading = true;
      this.getList(this.pagination.current, this.pagination.pageSize).then(res => {
        this.tableData = res.result.rows;
        this.tableKey++;
        this.pagination.total = res.result.count;
        this.showAllList && (this.pagination.pageSize = res.result.rows.length);
        this.loading = false;
        this.selectedRowKeys = [];
      });
    },
    handlePageChange ({ current }) {
      this.selectedRowKeys = [];
      this.pagination.current = current;
      this.refreshTable();
    },
    handleSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    customRowFun (record, index) {
      return {
        on: {
          click: event => {
          },
          dblclick: event => {
          },
          contextmenu: event => {
          },
          mouseenter: event => {
          },
          mouseleave: event => {
          }
        }
      };
    },
    customHeaderRowFun (column) {
      return {
        on: {
          click: event => {
          },
          dblclick: event => {
          },
          contextmenu: event => {
          },
          mouseenter: event => {
          },
          mouseleave: event => {
          }
        }
      };
    },
    handleAddClick () {
      console.log(Events);
      console.log(emitter);
      emitter.emit(Events.SHOW_ADD_EDIT_MODAL, {
        type: 'ADD'
      });
    },
    handleEditClick () {
      emitter.emit(Events.SHOW_ADD_EDIT_MODAL, {
        type: 'EDIT',
        id: this.selectedRowKeys[0]
      });
    },
    handleDeleteClick () {
      this.$confirm({
        title: '提示',
        content: '确定要删除吗?',
        onOk: () => {
          this.deleteData({ id: this.selectedRowKeys[0] }).then(res => {
            this.$message.success(res.msg);
            const tableLength = this.tableData.length;
            // 当前 table 只有一条数据 && 页码大于 1
            if (tableLength === 1 && this.pagination.current > 1) {
              this.pagination.current--;
            }
            this.refreshTable();
          }).catch(() => {
            this.$message.error('删除失败');
          });
        },
        onCancel: noop
      });
    }
  },
  render () {
    const on = { ...this.$listeners };
    const props = {
      ...this.$attrs,
      ...this.$props,
      ...{
        pagination: this.pagination,
        dataSource: this.tableData,
        columns: this.tableHeader
      }
    };
    this.showRowSelection && Object.assign(props, { rowSelection: { selectedRowKeys: this.selectedRowKeys, onChange: this.handleSelectChange } });
    const table = (
      <a-table
        on={on}
        props={props}
        size='small'
        bordered={true}
        scopedSlots={this.$scopedSlots}
        loading={this.loading}
        key={this.tableKey}
        row-key={record => record.id}
        onChange={this.handlePageChange}
        customRow={(record, index) => this.customRowFun(record, index)}
        customHeaderRow={column => this.customHeaderRowFun(column)}
      >
        {
          Object.keys(this.$slots).map(slot => {
            return (
              <template slot={slot}>{this.$slots[slot]}</template>
            );
          })
        }
      </a-table>
    );

    const buttonGroup = (
      <div style={{ 'margin-bottom': '12px' }}>
        <a-button-group>
          <a-button onClick={this.handleAddClick}>
            新增
          </a-button>
          <a-button
            onClick={this.handleEditClick}
            disabled={!(this.selectedRowKeys.length === 1)}
          >
            编辑
          </a-button>
          <a-button
            onClick={this.handleDeleteClick}
            disabled={!(this.selectedRowKeys.length >= 1)}
          >
            删除
          </a-button>
        </a-button-group>
      </div>
    );

    return (
      <div class="table-wrapper">
        {this.showButton && buttonGroup}
        {table}
      </div>
    );
  },
  mounted () {
    this.refreshTable();
    emitter.on(Events.REFRESH_TABLE, this.refreshTable);
  },
  beforeDestroy () {
    emitter.off(Events.REFRESH_TABLE);
  }
};

export default CgTable;
